#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
舆论监控系统演示脚本

展示如何使用新增的舆论监控功能。
"""

import asyncio
import logging
import uuid
from datetime import datetime

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)

# 导入舆论监控模块
from sentiment.analyzer import SentimentAnalyzer
from sentiment.keywords import KeywordManager
from anti_crawler.delays import DelayManager, DelayType
from monitoring.monitor import SentimentMonitor, MonitorTarget
from monitoring.rules import MonitoringRules
from monitoring.alerts import AlertManager
from crawlers.douyin.web.enhanced_crawler import EnhancedDouyinCrawler

async def demo_sentiment_analysis():
    """演示情感分析功能"""
    print("🔬 情感分析功能演示")
    print("=" * 50)
    
    analyzer = SentimentAnalyzer()
    
    # 测试文本示例
    test_comments = [
        "这家店的菜真的很好吃，服务态度也很好，强烈推荐！",
        "太难吃了，菜品质量很差，服务员态度也不好",
        "一般般吧，价格还算合理",
        "食物中毒了！！！这家黑店千万别去，垃圾！",
        "环境很好，很干净，菜品也新鲜",
        "坑人的店，宰客，价格虚高，服务差劲"
    ]
    
    print("📝 测试评论：")
    for i, comment in enumerate(test_comments, 1):
        print(f"{i}. {comment}")
    
    print("\n🧠 分析结果：")
    print("-" * 30)
    
    # 批量分析
    results = analyzer.batch_analyze(test_comments)
    
    for i, result in enumerate(results, 1):
        sentiment_emoji = {
            'positive': '😊',
            'negative': '😠', 
            'neutral': '😐'
        }.get(result['sentiment'], '❓')
        
        threat_level = "🟢" if result['threat_level'] <= 1 else "🟡" if result['threat_level'] <= 3 else "🔴"
        
        print(f"{i}. {sentiment_emoji} {result['sentiment'].upper()} | "
              f"得分: {result['score']:.3f} | "
              f"威胁: {threat_level} {result['threat_level']}/5")
        
        if result.get('keywords'):
            print(f"   关键词: {', '.join(result['keywords'][:3])}")
    
    # 统计分析
    comments_data = [{'text': comment} for comment in test_comments]
    stats = analyzer.get_statistics(comments_data)
    
    print(f"\n📊 统计结果：")
    print(f"   正面评论: {stats['positive']} ({stats['positive_rate']:.1%})")
    print(f"   负面评论: {stats['negative']} ({stats['negative_rate']:.1%})")
    print(f"   中性评论: {stats['neutral']}")
    print(f"   平均分数: {stats['avg_score']:.3f}")

async def demo_smart_delay():
    """演示智能延迟功能"""
    print("\n⏰ 智能延迟功能演示")
    print("=" * 50)
    
    delay_manager = DelayManager()
    
    # 模拟不同的延迟策略
    delay_types = [
        DelayType.HUMAN_LIKE,
        DelayType.ADAPTIVE,
        DelayType.RANDOM,
        DelayType.EXPONENTIAL
    ]
    
    for delay_type in delay_types:
        print(f"\n🎯 测试 {delay_type.value} 延迟:")
        
        # 执行3次延迟测试
        for i in range(3):
            start_time = datetime.now()
            delay_time = await delay_manager.wait(delay_type)
            actual_time = (datetime.now() - start_time).total_seconds()
            
            print(f"   第{i+1}次: 预期 {delay_time:.2f}s, 实际 {actual_time:.2f}s")
            
            # 记录请求结果（模拟）
            success = True  # 假设都成功
            delay_manager.record_request(success=success, response_time=delay_time)
        
        # 显示统计
        stats = delay_manager.get_statistics()
        print(f"   成功率: {stats['success_rate']:.1%}")
        print(f"   平均延迟: {stats['avg_delay']:.2f}s")

async def demo_enhanced_crawler():
    """演示增强爬虫功能"""
    print("\n🕷️ 增强爬虫功能演示")
    print("=" * 50)
    
    # 注意：这里只是演示代码结构，实际运行需要有效的Cookie配置
    print("⚠️  注意：演示模式，需要配置有效的Cookie才能实际爬取数据")
    
    try:
        crawler = EnhancedDouyinCrawler(
            enable_sentiment_analysis=True,
            enable_smart_delay=True
        )
        
        print("✅ 增强爬虫初始化成功")
        print(f"   - 情感分析: 启用")
        print(f"   - 智能延迟: 启用")
        
        # 展示爬虫统计信息
        stats = crawler.get_crawler_stats()
        print(f"   - 处理视频数: {stats['total_videos_processed']}")
        print(f"   - 处理评论数: {stats['total_comments_processed']}")
        
        # 模拟批量监控（需要真实视频URL）
        print("\n📺 批量监控功能（演示模式）:")
        print("   实际使用时，可以监控多个视频的评论舆情")
        print("   支持情感分析、威胁等级评估、用户影响力分析等")
        
    except Exception as e:
        print(f"❌ 演示过程中出现错误: {e}")
        print("   这通常是由于缺少必要的配置（如Cookie）导致的")

async def demo_monitoring_rules():
    """演示监控规则功能"""
    print("\n📋 监控规则功能演示")
    print("=" * 50)
    
    rules_engine = MonitoringRules()
    
    # 显示默认规则
    all_rules = rules_engine.get_all_rules()
    print(f"📚 默认规则数量: {len(all_rules)}")
    
    for rule in all_rules[:3]:  # 只显示前3个规则
        print(f"   🔹 {rule['name']}")
        print(f"      类型: {rule['rule_type']}")
        print(f"      严重程度: {rule['severity']}")
        print(f"      描述: {rule['description']}")
        print()
    
    # 模拟规则评估
    print("🧪 模拟规则评估:")
    
    # 模拟数据
    test_data = {
        'comments_analyzed': 50,
        'negative_comments': 25,
        'high_risk_comments': 5,
        'risk_level': 'high',
        'overall_sentiment': {'positive': 15, 'negative': 25, 'neutral': 10}
    }
    
    target_info = {
        'id': 'test_target',
        'name': '测试餐厅'
    }
    
    triggered_alerts = await rules_engine.evaluate_rules(test_data, target_info)
    
    print(f"   触发的告警数量: {len(triggered_alerts)}")
    for alert in triggered_alerts:
        print(f"   🚨 {alert['title']} ({alert['severity']})")
    
    # 规则统计
    rule_stats = rules_engine.get_rule_statistics()
    print(f"\n📊 规则统计:")
    print(f"   总规则数: {rule_stats['total_rules']}")
    print(f"   启用规则: {rule_stats['enabled_rules']}")
    print(f"   严重程度分布: {rule_stats['severity_distribution']}")

async def demo_alert_system():
    """演示告警系统功能"""
    print("\n🚨 告警系统功能演示")
    print("=" * 50)
    
    alert_manager = AlertManager()
    
    # 显示告警渠道配置
    channel_configs = alert_manager.get_channel_configs()
    print("📡 告警渠道状态:")
    for channel, config in channel_configs.items():
        status = "✅ 启用" if config['enabled'] else "❌ 禁用"
        print(f"   {channel}: {status}")
    
    # 发送测试告警
    print("\n📤 发送测试告警:")
    
    test_alert = {
        'rule_id': 'test_rule',
        'rule_name': '测试规则',
        'type': 'test',
        'severity': 'info',
        'title': '舆论监控系统测试告警',
        'content': '这是一条测试告警消息，用于演示告警系统功能。检测到负面评论增加，请关注。',
        'target_id': 'demo_target',
        'timestamp': datetime.now().isoformat()
    }
    
    success = await alert_manager.send_alert(test_alert)
    
    if success:
        print("   ✅ 测试告警发送成功")
    else:
        print("   ❌ 测试告警发送失败")
    
    # 显示告警统计
    alert_stats = alert_manager.get_statistics()
    print(f"\n📈 告警统计:")
    print(f"   总告警数: {alert_stats['total_alerts']}")
    print(f"   成功发送: {alert_stats['sent_alerts']}")
    print(f"   发送失败: {alert_stats['failed_alerts']}")
    print(f"   成功率: {alert_stats['success_rate']:.1%}")

async def demo_keyword_management():
    """演示关键词管理功能"""
    print("\n🏷️ 关键词管理功能演示")
    print("=" * 50)
    
    keyword_manager = KeywordManager()
    
    # 显示关键词统计
    stats = keyword_manager.get_statistics()
    print("📊 关键词统计:")
    print(f"   监控关键词总数: {stats['total_monitor']}")
    print(f"   负面关键词总数: {stats['total_negative']}")
    print(f"   正面关键词总数: {stats['total_positive']}")
    
    # 添加自定义监控关键词
    print("\n➕ 添加自定义关键词:")
    custom_keywords = ["我的品牌", "我的餐厅", "我的产品"]
    
    for keyword in custom_keywords:
        success = keyword_manager.add_monitor_keyword(keyword, "brands")
        if success:
            print(f"   ✅ 已添加: {keyword}")
        else:
            print(f"   ❌ 添加失败: {keyword}")
    
    # 测试关键词匹配
    print("\n🔍 关键词匹配测试:")
    test_text = "我觉得这个品牌的产品质量不错，值得推荐"
    
    matches = keyword_manager.is_monitor_keyword_matched(test_text)
    if matches:
        print(f"   匹配的关键词: {[match['keyword'] for match in matches]}")
    else:
        print("   未找到匹配的关键词")
    
    # 获取负面关键词示例
    negative_keywords = keyword_manager.get_negative_keywords("serious")[:5]
    print(f"\n⚠️ 严重负面关键词示例: {negative_keywords}")

async def main():
    """主演示函数"""
    print("🎯 舆论监控系统功能演示")
    print("=" * 60)
    print("本演示将展示新增的舆论监控功能，包括：")
    print("- 情感分析")
    print("- 智能延迟")
    print("- 增强爬虫")
    print("- 监控规则")
    print("- 告警系统") 
    print("- 关键词管理")
    print("=" * 60)
    
    try:
        # 运行各个演示
        await demo_sentiment_analysis()
        await demo_smart_delay()
        await demo_enhanced_crawler()
        await demo_monitoring_rules()
        await demo_alert_system()
        await demo_keyword_management()
        
        print("\n🎉 所有功能演示完成！")
        print("\n📝 使用说明:")
        print("1. 配置Cookie后可以进行实际的视频评论监控")
        print("2. 通过Web面板可以管理监控目标和查看结果")
        print("3. 可以自定义监控规则和告警方式")
        print("4. 支持多种延迟策略以避免被反爬")
        print("\n🚀 启动Web监控面板: python dashboard/web_dashboard.py")
        
    except Exception as e:
        print(f"❌ 演示过程中出现错误: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    asyncio.run(main())